package com.hdl.school.service;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hdl.school.utils.Constants;
import com.leectrl.utils.HexUtil;

import java.io.IOException;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class TCPClientService extends Service {
    Map<String, Socket> socketHashMap=new HashMap<>();
    private MyReceiver myReceiver;
    private String serviceIp;
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        SharedPreferences sharedPreferences=getSharedPreferences("school_iot", 0);
        String extraSerial=sharedPreferences.getString("c_setting_extraSerial",null);
        if(extraSerial!=null) {
            JSONObject extraSerialConfig = JSON.parseObject(extraSerial);
            if (extraSerialConfig != null && extraSerialConfig.containsKey("enable") && extraSerialConfig.getBoolean("enable")) {
               serviceIp=extraSerialConfig.getString("service_ip").trim();
               for(int i=10001;i<=10008;i++){
                   createSocket(i,null);
               }
                IntentFilter intentFilter=new IntentFilter(Constants.ACTION_TCP_MESSAGE);
                myReceiver=new MyReceiver();
               registerReceiver(myReceiver,intentFilter);
            }
        }
    }

    @Override
    public void onDestroy() {
        if(myReceiver!=null){
            unregisterReceiver(myReceiver);
        }
        super.onDestroy();
    }

    private void createSocket(final int port, String sendMsg){
        final String key=serviceIp+":"+port;
        Socket socket=null;
        if(socketHashMap.containsKey(key)){
            socket=socketHashMap.get(key);
            if(!socket.isConnected()){
                socket=null;
            }
        }
        if(socket==null){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        socketHashMap.put(key,new Socket(serviceIp,port));
                        if(sendMsg!=null){
                            socketHashMap.get(key).getOutputStream().write(HexUtil.hexToByteArray(sendMsg));
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

        }

    }

    private void sendMessage(String hexMsg,int port){
        final String key=serviceIp+":"+port;
        if(socketHashMap.containsKey(key)){
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Log.e("TCP",key+"==>"+hexMsg);
                        socketHashMap.get(key).getOutputStream().write(HexUtil.hexToByteArray(hexMsg));
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }else{
            createSocket(port,hexMsg);
        }

    }

    class MyReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
          String action=intent.getAction();
          if(action.equals(Constants.ACTION_TCP_MESSAGE)){
              sendMessage(intent.getStringExtra("code"),intent.getIntExtra("port",0));
          }
        }
    }
}